package org.xzx.shop_api.service;

import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import org.xzx.shop_api.config.QiniuConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Service
public class QiniuService {
    @Autowired
    private Auth auth;

    @Autowired
    private UploadManager uploadManager;

    @Autowired
    private final BucketManager bucketManager;

    @Autowired
    private Configuration configuration;

    @Autowired
    private QiniuConfig qiniuConfig;

    public QiniuService(BucketManager bucketManager) {
        this.bucketManager = bucketManager;
    }

    /*
     * 获取上传凭证
     * @param bucketName 存储空间名称
     * @return 上传凭证
      */
    public String getUploadToken(String bucketName) {
        return auth.uploadToken(bucketName);
    }

    /*
     * 获取默认存储空间的上传凭证
     * @return 上传凭证
      */
    public String getUploadToken() {
        return auth.uploadToken(qiniuConfig.getBucket());
    }

    /*
     * 上传文件
     * @param file 文件
     * @return 文件访问URL
     * @throws IOException
      */
    public String uploadFile(MultipartFile file) throws IOException {
        // 生成文件名
        String fileName = generateFileName(file.getOriginalFilename());
        // 上传文件
        Response response = uploadManager.put(file.getBytes(), fileName, getUploadToken());
        // 解析上传结果
        if (response.isOK()) {
            return qiniuConfig.getDomain() + "/" + fileName;
        }
        throw new RuntimeException("七牛云上传失败: " + response.bodyString());
    }

    /*
     * 上传文件流
     * @param inputStream 文件流
     * @param fileName 文件名
     * @return 文件访问URL
     * @throws IOException
     */


    public String uploadFile(InputStream inputStream, String fileName) throws IOException {
        // 生成文件名
        String newFileName = generateFileName(fileName);
        // 上传文件
        Response response = uploadManager.put(inputStream, newFileName, getUploadToken(), null, null);
        // 解析上传结果
        if (response.isOK()) {
            return qiniuConfig.getDomain() + "/" + newFileName;
        }
        throw new RuntimeException("七牛云上传失败: " + response.bodyString());
    }

    /*
     * 上传字节数组
     * @param data 字节数组
     * @param fileName 文件名
     * @return 文件访问URL
     * @throws IOException
     */
    public String uploadFile(byte[] data, String fileName) throws IOException {
        // 生成文件名
        String newFileName = generateFileName(fileName);
        // 上传文件
        Response response = uploadManager.put(data, newFileName, getUploadToken());
        // 解析上传结果
        if (response.isOK()) {
            return qiniuConfig.getDomain() + "/" + newFileName;
        }
        throw new RuntimeException("七牛云上传失败: " + response.bodyString());
    }

    /*
     * 删除文件
     * @param fileName 文件名
     * @throws QiniuException
     */
    public void deleteFile(String fileName) throws QiniuException {
        bucketManager.delete(qiniuConfig.getBucket(), fileName);
    }

    /*
     * 获取私有空间文件访问URL
     * @param fileName 文件名
     * @param expires 有效期（秒）
     * @return 文件访问URL
      */
    public String getPrivateFileUrl(String fileName, long expires) {
        return auth.privateDownloadUrl(qiniuConfig.getDomain() + "/" + fileName, expires);
    }

    /*
     * 生成唯一的文件名
     * @param originalFilename 原始文件名
     * @return 新文件名
     */
    private String generateFileName(String originalFilename) {
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        return UUID.randomUUID().toString().replace("-", "") + suffix;
    }
}
